const chromeMng = require('../mng/chromeMng.20180824'),
  log = require('../util/log')

exports.start = async () => {
  if (!chromeMng.client) {
    log('chrome未连接')
    return
  }
  if (chromeMng.busy) {
    log('chrome繁忙')
    return
  }
  log('占用chrome')
  chromeMng.busy = true
  // var result = await chromeMng.checkLoginJd()
  // if (!result) {
  //   log('未登录京东联盟，释放chrome')
  //   chromeMng.busy = false
  //   return
  // }
  chromeMng.loginJd().then(async result => {
    const {
      Network,
      Page,
      DOM,
      Runtime,
      Emulation
    } = chromeMng.client;
    await Page.navigate({
      url: 'https://media.jd.com/rest/report/detail'
    })
  }, result => {
    log(result)
    log('登录京东联盟失败，释放chrome')
    chromeMng.busy = false
  })
  step2()
}

async function step2(url) {
  if (!chromeMng.busy) {
    return new Promise(resolve => {
      resolve()
    })
  }
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = chromeMng.client;
  var {result} = await Runtime.evaluate({expression: 'location.href'})
  if (result.value == url) {
    return new Promise(resolve => {
      log('获取京东订单超时，释放chrome')
      chromeMng.busy = false
      resolve()
    })
  }
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      step2(result.value).then(result => {
        resolve(result)
      }, result => {
        reject(reject)
      })
    }, 5000)
  })
}
